package cn.tedu.meituanprogram.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {
   // @Value() 的作用是给变量赋值,${xxx}会去application.properties里面读取配置信息
    @Value("d:/files")
    private String dirPath;
    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
       String filename = picFile.getOriginalFilename();
       String suffix = filename.substring(filename.lastIndexOf("."));
       filename = UUID.randomUUID()+suffix;


       //准备日期相关的路径部分  /2023/02/14/
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = format.format(new Date());
        File dirFile = new File(dirPath+datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String filePath = dirPath+datePath+filename;
        //保存文件,异常抛出
        picFile.transferTo(new File(filePath));
        //把日期路径和文件名拼接后响应给客户 /2023/02/14/xxx.jpg
        return datePath+filename;

    }

    @RequestMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }
}
